package com.inspur_video.inspur_video.service;

import com.inspur_video.inspur_video.bean.Favorite;
import com.inspur_video.inspur_video.bean.tofront.FavoritesInfo;
import com.inspur_video.inspur_video.bean.video.Video;
import com.inspur_video.inspur_video.dao.FavoriteDao;
import com.inspur_video.inspur_video.dao.VideoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2018-08-13 21:40
 * @package com.inspur_video.inspur_video.service
 * @description
 */
@Service
@Transactional
public class FavoriteService {
    @Autowired
    FavoriteDao favoriteDao;
    @Autowired
    VideoDao videoDao;

    public boolean addFavorite(int uid, String vid) {
        Favorite favorite = new Favorite();
        favorite.setUId(uid);
        favorite.setVId(vid);
        favorite.setUTime(new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()));
        Favorite fallback = favoriteDao.save(favorite);
        if (fallback.getFId() != 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteFavorite(int uid, String vid) {
        return favoriteDao.deleteByUIdAndVId(uid, vid) != 0 ? true : false;
    }

    public List getFavorite(int uid) {
        List<Favorite> favorites = favoriteDao.findFavoritesByUId(uid, new Sort(Sort.Direction.DESC, "uTime"));
        List<FavoritesInfo> favoritesInfoList = new LinkedList<>();
        for (Favorite item : favorites) {

            Video videoItem = videoDao.findVideosByAIdEquals(item.getVId());

            FavoritesInfo favoritesInfo = new FavoritesInfo();
            favoritesInfo.setTime(item.getUTime());
            favoritesInfo.setDesc(videoItem.getVDescribe());
            favoritesInfo.setId(videoItem.getAId());
            favoritesInfo.setTitle(videoItem.getVTitle());

            favoritesInfoList.add(favoritesInfo);
        }
        return favoritesInfoList;
    }
}
